﻿using System;
using System.Globalization;
using System.IO;
using System.Web.Hosting;

namespace SlamCms.Logging
{
	public static class SlamCmsLogger
	{
		private readonly static string LogFile;

		static SlamCmsLogger()
		{
			if (HostingEnvironment.IsHosted)
				LogFile = HostingEnvironment.MapPath("~/App_Data/slamcms_log.txt");
			else
				LogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "slamcms_log.txt");
		}

		public static void Error(Exception ex, string message = null, params object[] args)
		{
			if (message == null)
				WriteInternal("Error: " + ex);
			else
				WriteInternal("Error " + string.Format(CultureInfo.InvariantCulture, message, args) +  " " + ex);
		}

		public static void Write(string message, params object[] args)
		{
			WriteInternal(string.Format(CultureInfo.InvariantCulture, message, args));
		}

		private static void WriteInternal(string message)
		{
			if (LogFile == null)
				return;

			try
			{
				using (var textWriter = File.AppendText(LogFile))
				{
					textWriter.WriteLine("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture), message);
				}
			}
			catch (Exception)
			{
			}
		}
	}
}
